package uk.ac.ebi.curtain.utils.file.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.locks.ReentrantLock;

/**
 * File: FastqChunkReader.java
 * Created by: mhaimel
 * Created on: Aug 8, 2011
 * CVS:  $Id: FastqChunkReader.java 1.0 Aug 8, 2011 12:55:14 PM mhaimel Exp $
 */

/**
 * @author mhaimel
 *
 */
public class FastqChunkReader extends AbstractChunkReader {
	
	public FastqChunkReader(InputStream in) {
		super(in);
	}
	
	protected ByteBuffer _next(ByteBuffer bb) throws IOException {
		int cnt = 0;
		int tmp = -1;
		while(cnt < 4){
			if(!bb.hasRemaining()){
				bb = increaseBuffer(bb);
			}
			tmp = in.read();
			switch (tmp) {
			case -1:
				if(bb.position() > 0){
					if(cnt == 3){
						// treat it like a new line
						++cnt;
						break;
					} else {
						throw new IOException("Unexpected EOF - unfinished entry >" + bb.asCharBuffer().toString()+"<");
					}
				}
				return null;
//					break; // NOT required
			case NL:
				++cnt;
			default:
				bb.put((byte)tmp);
				break;
			}
		}
		return bb;
	}

	protected ByteArrayOutputStream _next() throws IOException {
		bo.reset();
		int cnt = 0;
		int tmp = -1;
		while(cnt < 4){
			tmp = in.read();
			switch (tmp) {
			case -1:
				if(bo.size() > 0){
					if(cnt == 3){
						// treat it like a new line
						++cnt;
						break;
					} else {
						throw new IOException("Unexpected EOF - unfinished entry >" + bo.toString()+"<");
					}
				}
				return null;
//					break; // NOT required
			case NL:
				++cnt;
			default:
				bo.write(tmp);
				break;
			}
		}
		return bo;
	}
	
	public void close() throws IOException {
		in.close();
	}	
}
